<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model="uname" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model.number="age" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="sex">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="addlist">添加/修改</button>
    </div>
    <div>
      <table border="1" cellpadding="10" cellspacing="0">
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in list" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.uname }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.sex }}</td>
          <td>
            <button @click="del(item.id)">删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list: JSON.parse(localStorage.getItem('score-list')) || [],
      uname: '',
      sex: '',
      age: '',
      id: 0,
      gai: -1,
    }
  },
  methods: {
    //删除
    del(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    //添加
    addlist(id) {
      if (
        !this.uname ||
        this.age < 0 ||
        this.age > 100 ||
        this.age === '' ||
        !this.sex
      ) {
        return alert('请输合理')
      } else if (this.gai == -1) {
        this.list.push({
          id: this.list.length ? this.list.at(-1).id + 1 : 1,
          uname: this.uname,
          age: this.age,
          sex: this.sex,
        })
        this.uname = ''
        this.sex = ''
        this.age = ''
        //编辑了在修改
      } else {
        this.list.forEach((item) => {
          if (item.id == this.id) {
            item.uname = this.uname
            item.sex = this.sex
            item.age = this.age
            this.gai = -1
            this.uname = ''
            this.sex = ''
            this.age = ''
          }
        })
      }
    },
    //编辑
    edit(id) {
      this.list.forEach((item) => {
        if (item.id == id) {
          this.uname = item.uname
          this.sex = item.sex
          this.age = item.age
          this.id = item.id
        }
      })
      this.gai = 1
    },
  },
  //监测list 储存到本地
  watch: {
    list() {
      localStorage.setItem('score-list', JSON.stringify(this.list))
    },
  },
}
</script>
